import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:bot_toast/bot_toast.dart';
import 'package:thinking/entity/_.dart';
import 'SharedPreferences.dart';
import 'dart:convert' as convert;
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:flutter/services.dart' show rootBundle;
///工具类函数 主要用于dart逻辑

class Tool{
  /// 验证格式
  static bool isRegExp(String str,Type type) {
    switch(type){
      case Type.Phone:
        return new RegExp('^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$').hasMatch(str);
      case Type.PassWord:
        return new RegExp(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$").hasMatch(str);
      case Type.Email:
        return new RegExp(r"^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$").hasMatch(str);
      default:
        return false;
    }
  }


  /// 生成N位随机数
  static String randomBit([int len = 15]) {
    String scopeF = '123456789'; //首位
    String scopeC = '0123456789'; //中间
    String result = '';
    for (int i = 0; i < len; i++) {
      if (i == 0) {
        result = scopeF[Random().nextInt(scopeF.length)];
      } else {
        result = result + scopeC[Random().nextInt(scopeC.length)];
      }
    }
    return result;
  }
  ///存储个人信息
  static Future<bool> setUserList(UserList userList) async{

  try{
      await SPreferences().setString('token', userList.userToken);
      await SPreferences().setString('user_phone', userList.userData!.userPhone);
      await SPreferences().setString('user_PassWord', userList.userData!.userPassWord);
      await SPreferences().setString('user_HeadImg', userList.userData!.userHeadImg);
      if( userList.userData!.userNickName!=null)await SPreferences().setString('user_NickName', userList.userData!.userNickName);
      await SPreferences().setInt('user_Id', userList.userData!.userId);
      await SPreferences().setInt('user_LoginStatus', userList.userData!.userLoginStatus);
      await SPreferences().setString('user_UserInfo', convert.jsonEncode(userList.userData!.userUserInfo!.toJson()));
      return true;

  }catch(e){
    BotToast.showText(text: '用户异常!');
    print(e);
    return false;
  }


  }

  ///删除个人信息
  static Future<void> deleteUserList({bool isDeleteLogin:false}) async{

      await SPreferences().deleteData('token');
      await SPreferences().deleteData('user_phone');
      await SPreferences().deleteData('user_PassWord');
      await SPreferences().deleteData('user_HeadImg');
      await SPreferences().deleteData('user_NickName');
      await SPreferences().deleteData('user_Id');
      await SPreferences().deleteData('user_LoginStatus');
      await SPreferences().deleteData('user_UserInfo');
      if(isDeleteLogin == true){
        await SPreferences().setBool('isLogin', false);
      }

  }

  ///将数组分为子数组
  static List<List<T>> splitList<T>(List<T> list,int length){

    if(length <= 1){
      return [list];
    }

      int index = 1;
      List<List<T>> res = [];

      while(true){

        if(index*length<list.length){
          res.add(list.skip((index-1)*length).take(length).toList());
          index++;
          continue;
        }
        res.add(list.skip((index-1)*length).toList());
        break;
      }

      return res;
  }

  /*  时间戳转字符串
    * timestamp 时间戳
    * forMart ："y-m":年和月之间的符号,
    * "m-d":月和日之间的符号
    * "h-m":时和分之间的符号,
    * "m-s":分和秒之间的符号；
    * "m-a":是否显示上午和下午
    */
  static String dateAndTimeToString(var timestamp,
      {required Map<String, String> formart}) {
    if (timestamp == null || timestamp == "") {
      return "";
    }
    String targetString = "";
    final date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000);
    String year = date.year.toString();
    String month = date.month.toString();
    if (date.month <= 9) {
      month = "0" + month;
    }
    String day = date.day.toString();
    if (date.day <= 9) {
      day = "0" + day;
    }
    String hour = date.hour.toString();
    if (date.hour <= 9) {
      hour = "0" + hour;
    }
    String minute = date.minute.toString();
    if (date.minute <= 9) {
      minute = "0" + minute;
    }
    String second = date.second.toString();
    if (date.second <= 9) {
      second = "0" + second;
    }
    // String millisecond = date.millisecond.toString();
    String morningOrafternoon = "上午";
    if (date.hour >= 12) {
      morningOrafternoon = "下午";
    }

    if (formart["y-m"] != null && formart["m-d"] != null) {
      targetString = year + formart["y-m"]! + month + formart["m-d"]! + day;
    } else if (formart["y-m"] == null && formart["m-d"] != null) {
      targetString = month + formart["m-d"]! + day;
    } else if (formart["y-m"] != null && formart["m-d"] == null) {
      targetString = year + formart["y-m"]! + month;
    }

    targetString += " ";

    if (formart["m-a"] != null) {
      targetString += morningOrafternoon + " ";
    }

    if (formart["h-m"] != null && formart["m-s"] != null) {
      targetString += hour + formart["h-m"]! + minute + formart["m-s"]! + second;
    } else if (formart["h-m"] == null && formart["m-s"] != null) {
      targetString += minute + formart["m-s"]! + second;
    } else if (formart["h-m"] != null && formart["m-s"] == null) {
      targetString += hour + formart["h-m"]! + minute;
    }

    return targetString;
  }
  /*
  * 2021-05-22T10:37:06.000+00:00 => 1621679826000
  * 把标准时间格式转换成时间戳
  */
  static int timeToStamp(String str) {
    String _time = str;
    int _intendtime = DateTime.parse(_time).millisecondsSinceEpoch;
    return _intendtime;
  }

  ///防抖
  static debounce(Function func, Duration mill) {
    Timer? timer;
    Duration delay = mill;
      if (timer != null) {
        if(timer.isActive) timer.cancel();
      }
      timer = Timer(delay, () {
        func.call();
      });
  }

  ///rsa初始化
  static Future<Encrypter> rsaMain() async{
    String publicKeyStr = await rootBundle.loadString('lib/static/assets/rsa_public_key.pem');
    String privateKeyStr = await rootBundle.loadString('lib/static/assets/rsa_private_key.pem');
    RSAAsymmetricKey publicKey =  RSAKeyParser().parse(publicKeyStr);
    RSAAsymmetricKey privateKey =  RSAKeyParser().parse(privateKeyStr);
    Encrypter encryptMain = Encrypter(RSA(publicKey: publicKey as RSAPublicKey,privateKey: privateKey as RSAPrivateKey));
    return encryptMain;
  }

  ///rsa加密 加密后转成base64
  static Future<String> encodeString(Encrypter encryptMain ,String content) async{

    return encryptMain.encrypt(content).base64;
  }
  ///rsa分段解密
  static Future<String> decodeString(Encrypter encryptMain,String content) async{

    Uint8List sourceBytes = base64.decode(content);
    int inputLen = sourceBytes.length;
    int maxLen = 64;
    List<int> totalBytes = [];
    for (var i = 0; i < inputLen; i += maxLen) {
      int endLen = inputLen - i;
      Uint8List item;
      if (endLen > maxLen) {
        item = sourceBytes.sublist(i, i + maxLen);
      } else {
        item = sourceBytes.sublist(i, i + endLen);
      }
      totalBytes.addAll(encryptMain.decryptBytes(Encrypted(item)));
    }
    return utf8.decode(totalBytes);

  }

}

enum Type {
  Phone,
  PassWord,
  Email
}